#include "socket.h"
#include "uri.h"
#include "http.h"

URI * http_get_header(char *location) {

   URI *uri;
   char buffer[1024],*search,*ptr;

   uri = split_uri(location);

   uri->sockfd = sock_create(uri->host, uri->port, VERBOSE);
   if(uri->sockfd == -1) return NULL;
   uri->fp = fdopen(uri->sockfd, "r");

   //sock_send(sock->fd, "GET %s HTTP/1.1\r\n", uri->resource);
   sock_send(uri->sockfd, "GET / HTTP/1.1\r\n");
   sock_send(uri->sockfd, "Host: %s\r\n\r\n", uri->host);

   if(fgets(buffer, 1024, uri->fp) != NULL) {

      if( (search = strstr(buffer,"HTTP/1.1")) == NULL) return NULL;

      if( (search = strstr(buffer,"200")) != NULL) uri->response=200;
      else if( (search = strstr(buffer,"302")) != NULL) uri->response=302;

   }

   while(fgets(buffer, 1024, uri->fp) != NULL && strcmp(buffer,"\r\n") != 0) {

printf("%s", buffer);
      if( (search = strstr(buffer, "Location: ")) != NULL) {

         ptr = search+strlen("Location: ");
         search = strchr(ptr, '\r');
         search = (search == NULL) ? strchr(ptr, '\n'): NULL;
         search = (search == NULL) ? strchr(ptr, '\0'): NULL;
         sprintf(buffer, "%.*s", (int) (search-ptr), ptr);

         fclose(uri->fp);
         close(uri->sockfd);
         free(uri);
         return http_get_header(buffer);

      } else if( (search = strstr(buffer, "Content-Type: ")) != NULL) {

         ptr = search+strlen("Content-Type: ");
         search = strchr(ptr, ';');

         if(search != NULL) {

            sprintf(buffer, "%.*s", (int) (search-ptr), ptr);
            uri->content = strdup(buffer);

         } else {

            if( (search = strchr(ptr, '\r')) != NULL || (search = strchr(ptr, '\n')) != NULL ) {
               sprintf(buffer, "%.*s", (int) (search - ptr), ptr);
               uri->content = strdup(buffer);
            } else
               uri->content = strdup(ptr);

         }

      } else if( (search = strstr(buffer, "Content-Length: ")) != NULL) {

         ptr = search+strlen("Content-Length: ");
         if( (search = strchr(ptr, '\r')) != NULL || (search = strchr(ptr, '\n')) != NULL ) {
            sprintf(buffer, "%.*s", (int) (search-ptr), ptr);
            uri->length = atol( buffer );
         }

      }

   }

   fclose(uri->fp);
   uri->fp = NULL;
   close(uri->sockfd);

   return uri;

}
